import datetime

import jwt
from django.db import DatabaseError, IntegrityError
from django.db.models import Q
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from api.serializers import UserSerializer
from api.utils import gen_md5_digest, check_username, check_password, check_phoneno
from education.models import User
from my_education import settings


@api_view(('POST',))
def login(request: HttpRequest) -> HttpResponse:
    """登录"""
    username = request.data.get('username')
    password = request.data.get('password')
    if check_username(username) and check_password(password):
        password = gen_md5_digest(password)
        user = User.objects \
            .filter(Q(username=username) | Q(tel=username)) \
            .filter(password=password).first()
        if user:
            user.point += 3
            user.save()
            payload = {
                'exp': timezone.now() + datetime.timedelta(days=1),
                'userid': user.userid
            }
            # 生成token令牌
            token = jwt.encode(payload, settings.SECRET_KEY).decode()
            data = {
                'code': 20000, 'msg': '登录成功',
                'token': token, 'username': user.username
            }
        else:
            data = {'code': 20001, 'msg': '用户名或密码错误'}
    else:
        data = {'code': 20002, 'msg': '无效的用户名和密码'}
    return Response(data)


@api_view(('POST',))
def register(request: HttpRequest) -> HttpResponse:
    """注册"""
    # 这个参数需要用户点击前端页面的同意协议按钮
    agreement = request.data.get('agreement')
    if agreement:
        username = request.data.get('username')
        password = request.data.get('password')
        tel = request.data.get('tel')
        if check_username(username) and check_password(password) and check_phoneno(tel):
            # 创建用户对象 添加注册信息
            user = User()
            user.username = username
            user.password = gen_md5_digest(password)
            user.tel = tel
            try:
                user.save()
                data = {'code': 30000, 'msg': '注册成功，请登录'}
            except DatabaseError:
                data = {'code': 30001, 'msg': '用户名或手机号已被注册'}

        else:
            data = {'code': 30002, 'msg': '请输入有效的注册信息'}
    else:
        data = {'code': 30003, 'msg': '请勾选同意网站用户协议及隐私政策'}
    return Response(data)


@api_view(('POST',))
def check_mailbox(request: HttpRequest) -> HttpResponse:
    """查看邮箱"""
    userid = request.data.get('userid')
    user = User.objects.only('email').get(userid=userid)
    if user.email:
        data = {'code': 10000, 'msg': '查询成功', 'email': user.email}
    else:
        data = {'code': 10002, 'msg': '该用户没有绑定邮箱'}
    return Response(data)


@api_view(('POST',))
def bind_mailbox(request: HttpRequest) -> HttpResponse:
    """绑定邮箱"""
    userid = request.data.get('userid')
    email = request.data.get('email')
    user = User.objects.only('email').get(userid=userid)
    try:
        user.email = email
        user.save()
        data = {'code': 40001, 'msg': '绑定成功'}
    except IntegrityError:
        data = {'code': 4000, 'msg': '该邮箱已被绑定，请重新输入'}
    return Response(data)


@api_view(('POST',))
def change_mailbox(request: HttpRequest) -> HttpResponse:
    """更换邮箱"""
    userid = request.data.get('userid')
    email = request.data.get('email')
    user = User.objects.only('email').get(userid=userid)
    try:
        user.email = email
        user.save()
        data = {'code': 5001, 'msg': '绑定成功'}
    except IntegrityError:
        data = {'code': 5000, 'msg': '该邮箱已被绑定'}
    return Response(data)


@api_view(('POST', 'GET'))
def check_tel(request: HttpRequest) -> HttpResponse:
    """查看手机号"""
    userid = request.data.get('userid')
    user = User.objects.only('tel').get(userid=userid)
    if user.tel:
        data = {'code': 5000, 'msg': '查询成功', 'tel': user.tel}
    else:
        data = {'code': 50001, 'msg': '该用户没有绑定手机号'}
    return Response(data)


@api_view(('POST',))
def bind_tel(request: HttpRequest) -> HttpResponse:
    """绑定手机号"""
    userid = request.data.get('userid')
    tel = request.data.get('tel')
    user = User.objects.only('tel').get(userid=userid)
    if not user.tel:
        try:
            if check_phoneno(tel):
                user.tel = tel
                user.save()
                data = {'code': 60000, 'msg': '绑定成功', 'tel': user.tel}
            else:
                data = {'code': 60001, 'msg': '电话号码输入有误'}
        except IntegrityError:
            data = {'code': 60002, 'msg': '该手机号已被绑定'}
    else:
        data = {'code': 60003, 'msg': '已经绑定了手机号'}
    return Response(data)


@api_view(('GET',))
def unbind_tel(request: HttpRequest) -> HttpResponse:
    """解绑手机号"""
    userid = request.data.get('userid')
    user = User.objects.only('tel').get(userid=userid)
    if user:
        user.tel = None
        user.save()
        data = {'code': 3000, 'msg': '解绑成功'}
    else:
        data = {'code': 3001, 'msg': '该用户没有手机号'}
    return Response(data)


@api_view(('POST', ))
def change_tel(request: HttpRequest) -> HttpResponse:
    """更换手机号"""
    userid = request.data.get('userid')
    tel = request.data.get('tel')
    user = User.objects.only('tel').get(userid=userid)
    if check_phoneno(tel):
        user.tel = tel
        user.save()
        data = {'code': 4000, 'msg': '更改成功'}
    else:
        data = {'code': 4001, 'msg': '请输入正确的手机号'}
    return Response(data)


@api_view(('POST',))
def alter_password(request: HttpRequest) -> HttpResponse:
    """修改密码"""
    userid = request.data.get('userid')
    password = request.data.get('password')
    user = User.objects.get(userid=userid)
    if check_password(password):
        user.password = gen_md5_digest(password)
        user.save()
        data = {'code': 2000, 'msg': '密码修改成功'}
    else:
        data = {'code': 20001, 'msg': '密码不符合规则'}
    return Response(data)
